//Importer is a integration js: includ Object.js, Ajax.js, Class.js;

//**********************from Object.js begain*****************************************//


$ObjectFactory=function(){this.initialize.apply(this,arguments);}
$ObjectFactory.prototype={
		
	initialize : function(){
		this.prefix="biz.zheng.";
	},
		
	getPrefix :	function(){
		return this.prefix;
	},
	
	/* render name */
	renderName : function(iName){
		if((typeof(iName)!="string")||(!iName)||(parseInt(iName)))return false;
		var QName = iName.replace(/ /g,"");
		if( QName.indexOf("$")==0 )   QName=this.getPrefix()+QName.substr(1);
		if( QName.indexOf("ll.")==0 ) QName=this.getPrefix()+QName.substr(3);
		if( QName.indexOf("bz.")==0 ) QName=this.getPrefix()+QName.substr(3);
		
		var sEnd=QName.charAt(QName.length-1);
	    if(sEnd=="*"){
	    	QName=QName.substr(0,QName.length-1)+"_base";
	    }

		return QName;
	},

	/*to denine a varous as fn [or {} if fn==null] */
	define : function(iName,fn){
		var QName = this.renderName(iName);
		if(!QName)return false;
		return fn?this._defineFunc(QName,fn):this._defineName(QName)
	},
	
	/*	inner; to define a various as {}*/
	_defineName : function(QName){
		var pNames=QName.split(".");
		var pkgLength=0;
		var namedObj;
		for(var i=0;i<pNames.length;i++){
			pkgLength += (pNames[i].length+1);
			var pkgName = QName.substr(0,pkgLength-1);
			var pkgType = eval("typeof "+pkgName);
			if("undefined"==pkgType){
				//TODO: how about: object!=pkgType;
				namedObj = new Object();
				eval(pkgName+" = namedObj;");
			}else{
				eval("namedObj = pkgName;");
			}
		}
		return namedObj;
	},
	
	/* inner; to define a various as fn */
	_defineFunc : function (QName,fn){
		try{
			eval( " _____ = " + QName ); 
			if(_____) return  _____; //if no error,means been named,return old;
		}catch(e){}
		try{
			eval( " _____ = " + fn );
			this._defineName(QName);
			eval( QName + " = _____ " );
			return  _____ ;
		}catch(e){
			//alert("defineFunc for "+QName+":\n "+e.description)
		}
		return false;
	}
};

$objectFactory = new $ObjectFactory();
function $NameSpace(QName){return $objectFactory.define(QName);}
function $GlobalDefine(QName,fn){return $objectFactory.define(QName,fn);}
$GlobalDefine("$ObjectFactory","$ObjectFactory");
$GlobalDefine("$objectFactory","$objectFactory");

function NameSpace(QName){return $NameSpace(QName);}//@dpreciated;
function GlobalDefine(QName,fn){return $GlobalDefine(QName,fn);}//@dpreciated;
function packageNamed(QName){return $objectFactory.define(QName);}//@dpreciated;
function ClassNamed(QName){return $objectFactory.define(QName);}//@dpreciated;
function ObjectNamed(QName,fn){return $objectFactory.define(QName,fn);}//@dpreciated;
function globalNamed(QName,fn){return $objectFactory.define(QName,fn);}//@dpreciated;



function between(param,container){
	return  belongtoContainer(param,container);
}

function belongto(param,container){
	return  belongtoContainer(param,container);
}

//param need to be judged whether it belongs to container;
function belongtoContainer(param,container){
	var aObj = param;
	var cObj = container;
	if(!cObj)return false;//null,false,"",undifined;
	if(aObj==cObj)return true;
	
	var	isContained = false;
	switch(typeof(cObj)){
	 //case "undefined" : break;
	 case "boolean" :
		isContained = cObj;
	 break;
	 case "number" :
		isContained = (parseNumber(aObj)==cObj);
	 break;
	 case "string" :
			// need to extra processing.
			isContained = belongtoCollection(param,container);
	 break;
	 case "object" :
		if (cObj instanceof Array){
			isContained = belongtoArray(aObj,cObj);
		}else{
			isContained = belongtoObject(aObj,cObj);
		}
	 break;
	 case "function" :
		isContained = cObj.call(null,aObj);
		if(typeof(isContained)!="boolean"){
			isContained=false;
		}
	 break;
	 default :
	}
	return isContained;
	
}

function belongtoArray(param,objects){
	var aObj = param;
	var cObj = objects;
	var aNumber = parseNumber(aObj);
	for(var i = 0; i < cObj.length ; i++){
		if(	cObj[i]== aObj || parseNumber(cObj[i])==aNumber){
			return true;
		}
	}
	return false;
}

function belongtoObject(param,objects){
	var aObj = param;
	var cObj = objects;
	var aNumber = parseNumber(aObj);
	for(var key in cObj){
		if(	cObj[key]== aObj || parseNumber(cObj[key])==aNumber){
			return true;
		}
	}
	return false;
}

function belongtoCollection(param,aCollection){
	//if(typeof(aIterator)=="boolean")return aIterator;
	//section like "{-∞:2,4:6,∞}"; "{5,6;8}";"{(5.8,8]}";
	var tList= aCollection.replace(/\s/g,"");
	var minTokenIndex = tList.lastIndexOf("{");
	var maxTokenIndex = tList.indexOf("}");
	if( minTokenIndex<0 || minTokenIndex>=maxTokenIndex	){
		// if no collectiontoken, processing as a section;
		return belongtoSection(param,tList);
	}
	
	tList = tList.replace(",",";").substring(minTokenIndex+1,maxTokenIndex);
	var sections = tList.split(";");
	var matched	= false;
	for(var i=0;i<sections.length;i++){
		if(sections[i].indexOf(":")>-1){
			var newSection="["+sections[i].replace(":",",")+"]";
			if( belongtoSection(param,newSection) ){
				matched = true;
				break;
			}
		}else if( sections[i]== param ||
				  parseNumber(sections[i])==parseNumber(param)
		){
			matched = true;
			break;
		}
		
	}
	return matched;
}

/**
alert(between(0,"{0,2:+∞}" ));//true;
alert(between( any object,false)); //false;
alert(between( 1,true )); //true;
alert(between( 1,"true" )); //false;
var aaa={}; aaa.a=56;
alert(between(56,aaa )); //true;
var aab=[]; aab[1]=56;
alert(between(56,aab )); //true;
**/

//deep id recuit deep avoid no-end-loop
function objectToString(cObj,deep,pkey){
	//typeof(null)="object", should add an option for whether need show null / undefined;
	if(cObj==null)return "null";
	var toStr="",maxDeep=5;
	var myDeep = parseInt(deep);
	myDeep = (isNaN(myDeep)||myDeep>5)?5:myDeep;
	if( myDeep<=0 ) return toStr;//arrived maxDeep!
	
	switch(typeof(cObj)){
	 case "undefined" : ;
	 	toStr+="undefined"; 
	 	break;
	 case "function" :
	 	var func;
	 	func=cObj.toString();//show function source;
	 	func=func.substr(0,func.indexOf("{")); //only show function name;
	 	//func="({function})"; //only indicate it is a function;
	 	toStr+=func; 
	 	break;
	 case "object" :
	 	if(cObj instanceof Object){
	 		var	aValue;
		 	for( var key in cObj ){
		 		var qkey = pkey?(pkey+"."+key):key;
		 		// for debug: if(key=="xmlNode")aValue="({XMLNODE})";else 
		 		try{
			 		aValue = objectToString(cObj[key],myDeep-1,qkey);
			 	}catch(e){}
		 		//if(aValue) toStr += ( key+"="+aValue+"; " );
		 		if(aValue) toStr += ( "<br/>\n"+qkey+" = "+aValue+" ;" );
		 	}
	 	}else{
	 		//toStr += "NOT JS OBJECT";//like xml Node;
	 	}
		if(toStr)toStr="["+toStr+"]";
	 	break;
	 default ://boolean,number,string;
	 	toStr += cObj; //toStr= "" + cObj;
	}
	return toStr;
}

_objectMap=new Array();
function getObject(key){
	var objKey = key;
	if(!key){
		do{ objKey = "O"+Math.floor(10000*Math.random());//caps O;
		}while(_objectMap[objKey]);
	}
	if(!_objectMap[objKey])_objectMap[objKey]=new Array();
		_objectMap[objKey].key = objKey;
	return _objectMap[objKey];
}

function genObject(genHandle){
	var obj = null;
	switch(typeof genHandle){
		case "string" :
			//try{obj = eval(genHandle);}catch(e){}//error should throw;
			obj = eval(genHandle);
			if(typeof(obj)=="function")obj=obj();
			break;
		case "function" :
			obj = genHandle();
			break;
		default:
			obj = genHandle;
	}
	return obj;
}

function getCachedObject(key,fnHandle,oLocked){
	var oCached = getObject(key);
	if(!(oCached.cached && oCached.object) ){
		oCached.cached = true;
		oCached.object = genObject(fnHandle);
	}else if(oCached.locked){
		oCached.cached = true;
		oCached.object = genObject(fnHandle);
	}
		oCached.locked = oLocked; 
	return oCached;
}

function releaseCachedObject(key,oLocked){
	var oCached = getObject(key);
	if(	oCached.locked && (oCached.locked==oLocked)){
		oCached.locked = false;
	}
}

function getObjHandle(arrObjLists){
	   var objList = arrObjLists;
	   var returnObj = null;
	   for (var i=0; i<objList.length; i++) {
			 try {
			    returnObj = new ActiveXObject(objList[i]);
	   			//this.logger.info("succeed in getting obj: "+objList[i]);
				break;
			 }catch (e){
				if(i==(objList.length-1));//this.logger.error("Failure in getting obj from list"+arrObjLists);
			 }
	   }
	   return returnObj;
}


function getDomHandle(isAsync){
   var objList = ['MSXML2.DOMDocument.6.0','MSXML2.DOMDocument.3.0','MSXML3.DOMDocument','Msxml2.DOMDocument.4.0', 'Msxml2.DOMDocument', 'MSXML.DOMDocument', 'Microsoft.XMLDOM','Microsoft.DOMDocument'];
    var objReturn  = getObjHandle(objList);
   if(objReturn) objReturn.async = isAsync?true:false;
   return objReturn;
}

function createDocument() {
	if (typeof ActiveXObject !== "undefined") {
		createDocument = function() {
			if (typeof arguments.callee.activeXString != "string") {
				var versions = [ "MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument" ];
				for ( var i = 0, len = versions.length; i < len; i++) {
					try {
						var xmldom = new ActiveXObject(versions[i]);
						arguments.callee.activeXString = versions[i];
						return xmldom;
					} catch (error) {
						// TODO
					}
				}
			}
			return new ActiveXObject(arguments.callee.activeXString);
		};
	} else if (document.implementation && document.implementation.createDocument) {
		createDocument = function() {
			var _XMLDOM = document.implementation.createDocument("", "", null);

			_XMLDOM.parseError = {
				valueOf : function() {
					return this.errorCode;
				},
				toString : function() {
					return this.errorCode.toString()
				}
			};

			_XMLDOM.__initError__();

			_XMLDOM.addEventListener("load", function() {
				this.__checkForErrors__();
				this.__changeReadyState__(4);
			}, false);

			return _XMLDOM;
		};
	} else {
		createDocument = function() {
			throw new Error("No Document object avaliable.");
		};
	}

	return createDocument();
}
function getHttpHandle() {
  //var objList = ['Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
  var objReturn;
  //* IE7 also XMLHttpRequest;
  if(window&&window.XMLHttpRequest){// Mozilla, Safari,..
       objReturn = new XMLHttpRequest();
       /*
       if (objReturn.overrideMimeType) {
           objReturn.overrideMimeType('text/xml');
       }
       * */
  }else{
  		var objList = ['Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
  		objReturn = getObjHandle(objList);
  }
  return objReturn;
}

//from prototype, can't be replaced, put here because  $import>doHttpPost>fnBind>$A
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

function fnBind() {
  var args = $A(arguments), method = args.shift(), object = args.shift();
  var retval = function() {
    return method.apply(object, args.concat($A(arguments)));
  }
  retval.method = method;
  return retval;
}

function objectEval(obj,str){
	var method = function(){
		var innerReturn = eval(str);
		if(typeof(innerReturn)=="function"){
			innerReturn = innerReturn.apply(obj);
		}
		/*
		else if(typeof(objReturn)=="undefined"){
			var newStr = "this."+str; //if forget "this."
			innerReturn = eval(newStr);
			if(typeof(innerReturn)=="function"){
				innerReturn = innerReturn.apply(obj);
			}
		}
		* */
		return innerReturn;
	} 
	return method.apply(obj);
}
 
function doHandle(handle1,args){
	if(typeof(handle1)=="function"){
		handle1(args);
	}else if(typeof(handle1)=="string"){
		var handle2 ;
		try{handle2 = eval(handle1);}catch(e){}
		if(typeof(handle2)=="function"){
			handle2(args);
		}
	}
}



//**********************from Object.js end*****************************************//

//**********************from ajax.js end*****************************************//
function doLoadXml(surl) {
   	var objReturn = {};
		objReturn.debug += "succeed in get xml doc. \n";
		objReturn.doc = getDomHandle();
		objReturn.doc.load(surl);
	return objReturn;	
}

function isRemoteRequest(surl) {
	var isRemote = false;
	if(surl&&surl.substr(0,4).toUpperCase()=="HTTP"){//absolute path;
		isRemote = true;
	}else if(document&&document.location){//ralative path;
		if(document.location.protocol.substr(0,4).toUpperCase()=="HTTP"){
			isRemote = true;
		}
	}
	return isRemote;
}

function doHttpGet(surl,sdoc) {
	return doHttpPost(surl,sdoc,"GET");	
}

function doHttpPost(surl,sdoc,method,isForm,async) {
	if(!isRemoteRequest(surl)){
		return doLoadXml(surl);
	}
	//alert(surl);
	var qIndex = surl.indexOf("?");
	if((!sdoc) && qIndex>0){
		//if no doc, we can use post form for pass params, especially for no roma letter.
		method="POST";
		isForm=true;
		sdoc=surl.substr(qIndex+1);
		surl=surl.substr(0,qIndex);
	}
	
   	var objReturn = {};
	var oCacKey = "cachedHttpHandleObject";
	var oLocked = new Object();
     var xmlHttpHandle = getCachedObject(oCacKey,getHttpHandle,oLocked).object;
    if (!xmlHttpHandle) {
		objReturn.debug ="不能创建XMLHTTP对象!";
		releaseCachedObject(oCacKey,oLocked);
        return objReturn;
    }
    xmlHttpHandle.abort();
    xmlHttpHandle.onreadystatechange = fnBind(doHttpTransport,null,xmlHttpHandle,objReturn);

    xmlHttpHandle.open(method?method:"POST",encodeURI(surl),async?true:false);
    //if post form data, please use/take care encodeURI(postdata);
    if(isForm){
        //xmlHttpHandle.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        xmlHttpHandle.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    }
    xmlHttpHandle.send(sdoc?sdoc:null);
//    this.logger.debug(objReturn.text);
//    this.logger.debug(objReturn.xml);
	releaseCachedObject(oCacKey,oLocked);
    return objReturn;
}
	
function doHttpTransport(httpHandle,objReturn){
	objReturn.debug = "httpHandle.readyState = "+httpHandle.readyState+"\n";
	if(httpHandle.readyState==4){
		if(httpHandle.status==200){
		    //this.logger.debug("通讯完成");
		    //alert(httpHandle.responseText);
		    objReturn.debug = "ResponseHeaders:\n"+httpHandle.getAllResponseHeaders()+"\n";
			if(httpHandle.responseText==""){
				objReturn.debug += "responseText : Empty! \n";
				//this.logger.debug("服务器无返回消息,操作可能失败!");
			}else if(httpHandle.responseXML){
				/*
				if(httpHandle.responseXML.documentElement ){
					objReturn.doc = httpHandle.responseXML;
					//responseXML is XML DOMDocument 
					return;
				}else if(!httpHandle.responseXML.xml){
					objReturn.debug += "responseXML doc is empty, please use responseText.\n";
					objReturn.text=httpHandle.responseText;
					if(httpHandle.responseXML.parseError){
						objReturn.debug += httpHandle.responseXML.parseError.reason+"\n";
						objReturn.debug += httpHandle.responseXML.parseError.srcText;
					}
				}else{
				*/
					objReturn.debug += "succeed in get XML doc. \n";
					var xmldoc = objReturn.doc = getDomHandle();
					if( xmldoc==null ){
						objReturn.debug += " Can'tget XML DOMDocument Handler";
						objReturn.text=httpHandle.responseXML.xml;
						return;
					}
					xmldoc.loadXML(httpHandle.responseXML.xml||httpHandle.responseText);
				    if (xmldoc.parseError.errorCode != 0) {
				    	objReturn.debug +=("Error in line " + xmldoc.parseError.line +
						 " position " + xmldoc.parseError.linePos +
						 "\nError Code: " + xmldoc.parseError.errorCode +
						 "\nError Reason: " + xmldoc.parseError.reason +
						 "Error Line: " + xmldoc.parseError.srcText);
					 }
				    //objReturn.text=httpHandle.responseText;
						//objReturn.debug += objReturn.doc.documentElement.xml;
						//alert(httpHandle.responseText);
				//}
			}else{
				objReturn.text=httpHandle.responseText;
				//objReturn.debug += objReturn.text;
			}
		}else{
			objReturn.debug = "httpHandle.status = "+httpHandle.status+": "+httpHandle.statusText+".\n";
		    objReturn.debug+= "ResponseHeaders:\n"+httpHandle.getAllResponseHeaders()+"\n";
		}
	}
}

//**********************from ajax.js end********************************************//

//**********************from Class.js begin*****************************************//
//20090326from Handle.js
//dojo.provide("$lang");
//dojo.require("$lang");

//$NameSpace("$lang.Class");
$Class=function(){this.initialize.apply(this, arguments);}
$GlobalDefine("$Class","$Class");
$Class.prototype={
	initialize : function(){
		this.newClassText="function(){if(this.initialize)this.initialize.apply(this, arguments);}";
	},
	
	create : function(QName){
	    return $GlobalDefine(QName,this.newClassText);
	},

	define : function(QName){
		return this.create(QName);
	},
	
	get : function(iName){
		var QName = $objectFactory.renderName(iName);
		if(!QName)return;
		var myType = eval("typeof "+QName);
		if("function"==myType){
			eval("var _____ = "+QName);
			return _____;
		}else{
			throw new Error(0,"can't get class for "+iName);
		}
	}
}

$class = new $Class();
$GlobalDefine("$class","$class");

function $ClassImport(QName){return $objectFactory.define(QName);}//TODO

function $ClassCreate(QName){return $objectFactory.define(QName);}//@depreciated;
function $ClassDefine(QName){return $objectFactory.define(QName);}//@depreciated;







//$NameSpace("$lang.ClassLoader");
//below should in ClassLoder.js;
$ClassLoader=$class.create("$lang.ClassLoader");
$ClassLoader.prototype={
		
	initialize : function(){
		this.loadedCSS=[];
		this.loadedJS=[];
		this.extNames=this.genExtNames();
	},
	
	genExtNames : function(){
		var extNames=[];
		extNames["js"]=".js";
		extNames["css"]=".css";
		return extNames;
	},
	
	getExtName : function(type){
		return this.extNames[type];
	},
	getContextPath : function(){
		var cPath = "/";
		if(typeof(appConfig)=="string"){
			cPath = appConig.getContextPath();
		}else if(typeof(requestContextPath)=="string"){
			cPath = requestContextPath;
		}else if(typeof(appContextPath)=="string"){
			cPath = appContextPath;
		}
		return this.renderPath(cPath);
	},
	
	/* 
	 * load('include.mian', 'js');
	 * load('style.xp;style.vista', 'css');
	 */
	load : function (names, type){
		var msg = "";//should use HashMap;
		try{
		  var arr = names.replace(/;/g,",").split(",");
		  for(var i=0;i<arr.length;i++){
		  	try{
		  		this.loadByName(arr[i],type);
		  	}catch(e){
		  		msg+=("\nloading "+arr[i]+" : "+e.description);
		  	}
		  }
		}catch(e){
	  		msg+=("\nloading : "+names+" : "+e.description);
		}
		if(msg){
			alert("$import(,) has some error: "+msg);
			throw new Error(0,msg);
		}
	},

	/** @inner	**/
	loadByName : function(iName,type){
		var QName = $objectFactory.renderName(iName);
		if(!QName)return;

		/* reflect invoke;
		var fn = eval("this.load"+type.toUpperCase());
		if(typeof(fn)=="function"){
			(fnBind(fn,this,QName))();
		}
		*/
		if (type == "css") {
			this.loadCSS(QName);
		} else if(type=="i18n") {
			this.loadI18N(QName);
		} else{
			this.loadJS(QName);
		}
	},

	/** @inner	**/
	loadCSS : function (QName) { 
		if( QName.length<1 || this.loadedCSS[QName] ) return false;
		var mUrl = QName.replace(/[\.]/g,"/")+this.getExtName("css");
		var fUrl = this.getContextPath()+mUrl;
	
		var oHead = document.getElementsByTagName('HEAD').item(0); 
		var oDOM = document.createElement( "link" ); 
			oDOM.rel = "stylesheet"; 
			oDOM.type = "text/css"; 
			oDOM.href = fUrl; 
		oHead.appendChild( oDOM ); 
		this.loadedCSS[QName]=mUrl;
		return true;
	}, 
	 
	/**	@inner **/
	loadJS : function(QName) { 
		if( QName.length<1 || this.loadedJS[QName] ) return false;
		var mUrl = QName.replace(/[\.]/g,"/")+this.getExtName("js");
		var fUrl = this.getContextPath()+mUrl;
		//can't use post, otherwise http 412 error;
		var objReturn = doHttpPost(fUrl,null,"GET");
	    if(!objReturn.text)return false;
	    // jsLoader use     document.writeln("<scri"+"pt src='"+url+"' type='text/javascript'></sc"+"ript>");
	    //but it can't ensure the js loaded complete order.
	    // from dojo, seems can't run.
	    /**
	    var _prefix = "(function(){";
		var _suffix = "})()";
	    //1.eval(objReturn.text);
		//2.objectEval(window,_prefix + objReturn.text + _suffix);
		//3.objectEval(window,objReturn.text);
	    */
	    //*
	 	var oHead = document.getElementsByTagName('HEAD').item(0); 
		var oDOM = document.createElement( "script" ); 
			oDOM.language = "javascript"; 
			oDOM.type = "text/javascript"; 
			//oDOM.id = sId; 
			//oDOM.defer = true; 
			oDOM.text =  objReturn.text; 
			//can't use oDOM.src =  fUrl
		oHead.appendChild( oDOM );
		//alert(oDOM.outerHTML)
		//*/  
		this.loadedJS[QName]=mUrl;
		return true;
	},
	
	renderPath:	function(srcPath){
		var path = srcPath;
		var sEnd=path.charAt(path.length-1);
	    if(sEnd!="\\" && sEnd!="/"){
	    	path=path+"/";
	    }
		return path;
	}

}

$classLoader = new $ClassLoader();

function $import(names, type){
	$classLoader.load(names, type?type:"js");
}
function $importJS(names){ $import(names, "js");}
function $importCSS(names){$import(names, "css");}


//**********************from ClassLoader.js end*****************************************//


$import("$util.HashMap;$util.AppConfig;$lang.prototype");
$import("$util.dom;$util.Listener;$util.xml;$util.Assert;");
$import("$lang.Math; $lang.String; $lang.Array; $util.Cookie; ");
